#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Author : fanzf
# @Version：V 0.1
# @File : utils.py
# @desc : 用户登录信息数据库模型，如：登录后的session和cookie
import os
from datetime import datetime, timedelta, time
from flask import current_app
from app.invokeEXE import login_web
import json
import psutil


def transferDate2Timestamp(date_str):
    time_format = "%Y/%m/%d %H:%M"
    dt_object = datetime.strptime(date_str, time_format)
    return int(dt_object.timestamp() * 1000)


def buildCookieStr(cookie):
    cookie_str = ["{}={}".format(key, value) for key, value in cookie.items()]
    result = ";".join(cookie_str)
    current_app.logger.debug("request head cookie is {}".format(result))
    return result


def dateTimeScope(yesterday, time_format):
    start_time = datetime.combine(yesterday, datetime.min.time())  # 00:00:00
    end_time = datetime.combine(yesterday, datetime.max.time())  # 23:59:59
    if time_format == 1:
        start_time_str = start_time.strftime('%Y-%m-%d %H:%M:%S')
        end_time_str = end_time.strftime('%Y-%m-%d %H:%M:%S')
    if time_format == 2:
        start_time_str = start_time.strftime('%Y-%m-%d+%H:%M:%S')
        end_time_str = end_time.strftime('%Y-%m-%d+%H:%M:%S')
    if time_format == 3:
        start_time_str = start_time.strftime('%Y-%m-%d %H:%M')
        end_time_str = end_time.strftime('%Y-%m-%d %H:%M')
    return start_time_str, end_time_str


def batchDate(day, batch_date):
    if not batch_date:
        today = datetime.now().date()
    else:
        today = datetime.strptime(batch_date, '%Y-%m-%d').date()
    yesterday = today - timedelta(days=day)
    return yesterday.strftime('%Y-%m-%d')


def batchTodayDate():
    batch_date_today = datetime.now().date().strftime('%Y-%m-%d')
    return batch_date_today


def reportTimeScope(batch_date):
    date_batch = datetime.strptime(batch_date, '%Y-%m-%d').date()
    start_time = datetime.combine(date_batch, datetime.min.time())  # 00:00:00
    start_time = start_time.strftime('%Y-%m-%d %H:%M:%S')
    end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 当前时间
    return start_time, end_time


def signTimestamp():
    current_time = datetime.now()
    current_time_milliseconds = int(current_time.timestamp() * 1000)
    return current_time_milliseconds


def checkTaskSwitch(app, batch_date):
    if not batch_date:
        not_execute_task = app.config["not_execute_task"]
        if not_execute_task:
            try:
                app.logger.info("获取不执行定时任务的配置：{}".format(not_execute_task))
                numbers = list(map(int, not_execute_task.split('-')))
                start_hour, end_hour = numbers[0], numbers[1]
                start_time = time(start_hour, 0, 0)  # 22:00:00
                end_time = time(end_hour, 0, 0)  # 09:00:00
                now = datetime.now().time()
                # 判断区间（需要考虑跨天）
                if start_time <= end_time:
                    # 不跨天，例如 08:00-09:00
                    in_range = start_time <= now <= end_time
                else:
                    # 跨天，例如 22:00-09:00
                    in_range = now >= start_time or now <= end_time
                return in_range
            except Exception as e:
                app.logger.error("checkTaskSwitch exception：{}".format(e))
        else:
            return False


def terminate_driver_pid(app, project_dir, pid_key):
    file_path = os.path.join(project_dir, 'autoLogin', 'config', 'driver_pid.json')
    # 读取 PID
    with open(file_path, 'r') as f:
        driver_pid = json.load(f)[pid_key]

    try:
        # 获取 chromedriver 进程
        driver_process = psutil.Process(driver_pid)

        # 递归终止所有子进程（包括 chrome 浏览器）
        children = driver_process.children(recursive=True)
        for child in children:
            child.terminate()
        driver_process.terminate()

        # 等待进程退出
        psutil.wait_procs([driver_process] + children, timeout=5)
        app.logger.info("Browser closed successfully.")
        # 清空删除的pid
        with open(file_path, 'r+', encoding='utf-8') as f:
            data = json.load(f)  # 1. 读
            data['mai_zuo_driver_pid'] = None  # 2. 改
            f.seek(0)  # 3. 写回
            json.dump(data, f, ensure_ascii=False, indent=4)
            f.truncate()
    except psutil.NoSuchProcess:
        app.logger.info("Process already terminated.")


def mao_yan_Flask(logger, project_dir):
    # 启动猫眼转发服务器（本地部署）
    maoyan_server = "run.exe"
    maoyan_server_path = os.path.join(project_dir, "autoLogin", "maoyanflask", maoyan_server)
    login_web(logger, maoyan_server_path, maoyan_server, "NonBlocking")


def loginMaiZuo(logger, project_dir):
    # 登录麦座
    exe_file_name1 = "loginMaizuo.exe"
    logger.debug("开始执行 {}".format(exe_file_name1))
    exe_file_name1_path = os.path.join(project_dir, exe_file_name1)
    login_web(logger, exe_file_name1_path, project_dir, "Blocking")
    logger.debug("执行 {} 完成".format(exe_file_name1))


def loginMaoYan(logger, project_dir):
    # 登录猫眼
    exe_file_name2 = "loginMaoYan.exe"
    logger.debug("开始执行 {}".format(exe_file_name2))
    exe_file_name2_path = os.path.join(project_dir, exe_file_name2)
    login_web(logger, exe_file_name2_path, project_dir, "Blocking")
    logger.debug("执行 {} 完成".format(exe_file_name2))


def parse_maizuo_cookie(app, project_root_dir):
    maizuo_file_path = os.path.join(project_root_dir, 'autoLogin', 'config', 'cookie_maizuo.json')
    app.config['COOKIE_MAIZUO'] = parseCookies(maizuo_file_path)


def parse_maoyan_cookie(app, project_root_dir):
    maoyan_file_path = os.path.join(project_root_dir, 'autoLogin', 'config', 'cookie_maoyan.json')
    app.config['COOKIE_MAOYAN'] = parseCookies(maoyan_file_path)


def parseCookies(path_cookie):
    with open(path_cookie, 'r', encoding='utf-8') as file:
        config = json.load(file)
    if not config:
        config = dict
    return config





